#include "mainwindow.h"
#include "ui_mainwindow.h"
#include<QPlainTextEdit>
#include<QFileDialog>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    //获取菜单栏
    QMenuBar*menubar = this->menuBar();

    //添加菜单
    QMenu*menu = new QMenu("文件");
    menubar->addMenu(menu);

    //添加菜单项
    QAction*action1 = new QAction("打开");
    QAction*action2 = new QAction("保存");
    menu->addAction(action1);
    menu->addAction(action2);

    //指定一个输入框
    QPlainTextEdit *edit =new QPlainTextEdit();
    QFont font;
    font.setPointSize(20);
    edit->setFont(font);
    this->setCentralWidget(edit );

    //连接QActio 的信号槽

    connect(action1,&QAction::triggered,this,&MainWindow::handActio1);
    connect(action2,&QAction::triggered,this,&MainWindow::handActio2);

}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::handActio1()
{
    //先弹出一个打开文件对话框
    QString path = QFileDialog::getOpenFileName(this);

    //把文件名显示到状态栏中
    QStatusBar* statusbar = this->statusBar();
    statusbar->showMessage(path);//显示路劲

    //根据用户选择的路劲，构造一个QFile对象
    QFile file(path);
    bool ret = file.open(QIODevice::ReadOnly);
    if(!ret)
    {
        statusbar->showMessage(path + "打开文件失败!");
        return;

    }


    //读取文件

    QString text =  file.readAll();


    //关闭文件
    file.close();

    //读取的内容设置到输入框中
    edit->setPlainText(text );

}

void MainWindow::handActio2()
{
    //弹出保存文件对话框
    QString path = QFileDialog::getSaveFileName(this);

    //在状态栏显示文件名
    QStatusBar* statusbar = this->statusBar();
    statusbar->showMessage(path);

    //根据选择的路劲，构造一个QFile对象 ，并打开文件
    QFile file(path);
    bool ret = file.open(QFile::WriteOnly);
    if(!ret)
    {
        statusbar->showMessage(path+ "打开失败");
        return;
    }

    //写文件
    const QString& text =edit ->toPlainText();
    file.write(text.toUtf8());

    //关闭文件
    file.close();
}

